import React, { useEffect } from 'react';
import { Form as RemixForm, useActionData, useLocation, useNavigation } from '@remix-run/react';
import { Button, Input, Card } from 'antd';
import { useAuthStore } from '~/stores/auth';
import { useNavigate } from '@remix-run/react';
import { json, ActionFunction } from '@remix-run/node';
import { authApi } from '~/services/api';
import { Loading } from '~/components/Loading';
import { ErrorMessage } from '~/components/ErrorMessage';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { App as AntdApp } from 'antd';

export const action: ActionFunction = async ({ request }) => {
  const formData = await request.formData();
  const username = formData.get('username');
  const password = formData.get('password');

  try {
    const response = await authApi.login({
      username: username as string,
      password: password as string
    });
    return json({
      success: true,
      data: response.data
    });
  } catch (error: any) {
    return json({
      success: false,
      error: error.response?.data?.message || '登录失败'
    });
  }
};

export default function Login() {
  const navigate = useNavigate();
  const actionData = useActionData<typeof action>();
  const setAuth = useAuthStore((state: any) => state.setAuth);
  const token = useAuthStore((state: any) => state.token);
  const navigation = useNavigation();
  const { message } = AntdApp.useApp();
  const location = useLocation();

  // 移除第一个 useEffect

  useEffect(() => {
    if (actionData?.success) {
      setAuth(actionData.data.token, actionData.data.user);
      message.success('登录成功');
      // 直接在这里处理跳转
      // const from = location.state?.from || '/dashboard';
      // navigate(from, { replace: true });
    } else if (actionData?.error) {
      message.error(actionData.error);
    }
  }, [actionData, setAuth, message, navigate, location]);

  // 合并重定向逻辑
  useEffect(() => {
    if (token) {
      const from = location.state?.from || '/dashboard';
      navigate(from, { replace: true });
    }
  }, [token, navigate, location]);

  if (navigation.state === 'loading') {
    return <Loading />;
  }

  return (
    <div className="flex h-screen items-center justify-center bg-gradient-to-r from-blue-500 to-purple-600">
      <Card
        title={
          <div className="text-center text-2xl font-bold text-gray-800 mb-2">
            ASAP CMS
          </div>
        }
        className="w-[420px] shadow-2xl"
      >
        <RemixForm method="post" className="space-y-6">
          <div>
            <Input
              name="username"
              placeholder="用户名"
              required
              size="large"
              prefix={<UserOutlined className="text-gray-400" />}
            />
          </div>
          <div>
            <Input.Password
              name="password"
              placeholder="密码"
              required
              size="large"
              prefix={<LockOutlined className="text-gray-400" />}
            />
          </div>
          <Button
            type="primary"
            htmlType="submit"
            loading={navigation.state === 'submitting'}
            block
            size="large"
            className="mt-8"
          >
            登录
          </Button>
          {/* {actionData?.error && (
            <ErrorMessage message={actionData.error} />
          )} */}
        </RemixForm>
      </Card>
    </div>
  );
}